// pages/index/index.js
import { categoryApi, shopApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { ORDER_STATUS, SHOP_STATUS } from '../../utils/constants.js'

const app = getApp()

Page({
  data: {
    loading: true,
    shopStatus: SHOP_STATUS.OPEN,
    categories: [],
    selectedCategoryId: null,
    userInfo: null,
    cartCount: 0
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 更新购物车数量
    this.updateCartCount()
    
    // 更新用户信息
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },

  onPullDownRefresh() {
    this.loadData()
  },

  onReachBottom() {
    // 可以在这里实现加载更多功能
  },

  // 初始化页面
  async initPage() {
    try {
      await this.loadData()
    } catch (error) {
      console.error('页面初始化失败:', error)
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  // 加载数据
  async loadData() {
    try {
      // 并行加载店铺状态和分类数据
      const [shopStatusRes, categoriesRes] = await Promise.all([
        shopApi.getStatus(),
        categoryApi.getList({ type: 1 }) // 获取菜品分类
      ])

      // 更新店铺状态
      if (shopStatusRes.code === 1) {
        this.setData({
          shopStatus: shopStatusRes.data
        })
        app.globalData.shopStatus = shopStatusRes.data
      }

      // 更新分类数据
      if (categoriesRes.code === 1) {
        const categories = categoriesRes.data
        this.setData({
          categories,
          selectedCategoryId: categories.length > 0 ? categories[0].id : null
        })
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 更新购物车数量
  updateCartCount() {
    app.updateCartCount()
    this.setData({
      cartCount: app.globalData.cartCount
    })
  },

  // 选择分类
  selectCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    this.setData({
      selectedCategoryId: categoryId
    })
  },

  // 跳转到分类页面
  goToCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    const categoryName = e.currentTarget.dataset.name
    
    wx.navigateTo({
      url: `/pages/category/category?id=${categoryId}&name=${encodeURIComponent(categoryName)}`
    })
  },

  // 跳转到购物车
  goToCart() {
    if (!checkLoginAndRedirect()) return
    
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },

  // 跳转到个人中心
  goToProfile() {
    wx.switchTab({
      url: '/pages/profile/profile'
    })
  },

  // 跳转到登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  // 搜索功能
  onSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  // 店铺状态提示
  showShopStatusTip() {
    const status = this.data.shopStatus
    const message = status === SHOP_STATUS.OPEN ? '店铺正在营业中' : '店铺已打烊，请明天再来'
    
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    })
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '美味外卖，尽在指尖',
      path: '/pages/index/index',
      imageUrl: '/images/share.jpg'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '美味外卖，尽在指尖',
      imageUrl: '/images/share.jpg'
    }
  }
})
